<template>
  <div class="biz-container">
    <table-layout :haveSider="false">
      <template #searchBox>
        <search-layout
          :formInfos="q_formInfos"
          :formDatas="q_formDatas"
          message=""
          @onFind="onFind"
          @onChangeType="onChangeType"
        ></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn
          :addData="false"
          @onAddData="onAddData"
          :delectData="false"
          @onDelectData="onDelectData"
        >
          <template #cusBtn>
            <a-button
              type="primary"
              @click="onMerge"
            >合并配送</a-button>
          </template>
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <a-list-table
          :columns="columns"
          :tableData="listdata"
          :pagination="pagination"
          :isSelecttion="true"
          :loading="loading"
          :scroll="{y:slotData.tableHeight}"
          :renderStateByField="['saleOrderState']"
          @onTableChange="handleTableChange"
          @onselectChange="onselectChange"
          @onAction="onAction"
          :links="links"
          @onTouchlinkCell="onTouchlinkCell"
        >
        </a-list-table>
      </template>
    </table-layout>
    <toDeliveryModal
      ref="modal"
      @ok="handleModalSaveOk"
      @close="handleModalCancel"
    />
    <!-- <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" /> -->
    <viewSaleOrderModal
      ref="viewSaleOrderModal"
      @ok="handleModalSaveOk"
      @close="handleModalCancel"
    />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import toDeliveryModal from './toDeliveryModal'
import viewSaleOrderModal from '../saleOrder/viewModal.vue'
// import viewModal from './viewModal'
import {
  getByConditions,
  getByConditionsCount,
} from '../saleOrder/saleOrder'


const columns = [
  { title: '采购类型', dataIndex: 'saletype', key: 'saletype', align: 'center' },
  { title: '客户名称', dataIndex: 'customerName', key: 'customerName', align: 'center' },
  { title: '销售单号', dataIndex: 'saleOrderNo', key: 'saleOrderNo', align: 'center', scopedSlots: { customRender: 'saleOrderNo' } },
  // { title: '销售单名称', dataIndex: 'saleOrderName', key: 'saleOrderName', align: 'center',},
  { title: '客户订单号', dataIndex: 'purOrderNo', key: 'purOrderNo', align: 'center' },
  { title: '送货类型', dataIndex: 'deliveryType', key: 'deliveryType', align: 'center' },
  { title: '订单数量', dataIndex: 'num', key: 'num', align: 'center' },
  { title: '已执行数量', dataIndex: 'execNum', key: 'execNum', align: 'center' },
  // { title: '订单状态', dataIndex: 'saleOrderState', key: 'saleOrderState', align: 'center' ,scopedSlots: { customRender: 'saleOrderState' }},
  // { title: '配送中数量', dataIndex: 'deliveryNum', key: 'deliveryNum', align: 'center' },
  // { title: '含税总价(元)', dataIndex: 'totalPrice', key: 'totalPrice', align: 'center',scopedSlots: { customRender: 'tofixed2' }  },
  // { title: '应收金额(元)', dataIndex: 'receivableAmount', key: 'receivableAmount', align: 'center' },
  // { title: '税费(元)', dataIndex: 'taxes', key: 'taxes', align: 'center' },
  // { title: '已收金额(元)', dataIndex: '	paidAmount', key: '	paidAmount', align: 'center' },
  { title: '操作', dataIndex: 'action', key: 'operation', width: 180, align: 'center', scopedSlots: { customRender: 'action' } },
]
let links = ['saleOrderNo',]

export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    viewSaleOrderModal,
    // viewModal, 
    toDeliveryModal
  },
  data () {
    return {
      columns: columns,
      listdata: [],
      links: links,
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
      },
      // 查询表单
      q_formInfos: [
        { label: '采购类型', name: 'saletype', type: 'dicselect', dicName: 'purType', placeholder: '采购类型' },
        { label: '客户名称', name: 'customerPid', type: 'customer', placeholder: '客户名称' },
        { label: '销售单号', name: 'pid', type: 'saleOrderSelect', placeholder: '销售单号' },
        { label: '客户订单号', name: 'purOrderNo', type: 'input', placeholder: '客户订单号' },
        // { label: '销售单号', name: 'saleOrderNo', type: 'input', placeholder: '销售单号' },
        { label: ['查询', '重置'], type: 'botton' }
      ],
      // 查询表单绑定数据
      q_formDatas: {
        pid: null,
        saletype: null,
        saleOrderNo: null,
        purOrderNo: null,
        customerPid: null,
        saleOrderState: '待配送`#`部分配送`#`部分收货'
      },
      pData: {}, // 条件查询参数
      isJump: false,
      optText: '确认订单',
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false
    }
  },
  computed: {},
  watch: {
    //监听路由，只要路由有变化(路径，参数等变化)都有执行下面的函数，你可以
    $route: {
      handler: function (val, oldVal) {
        //created事件触发的函数可以在这里写... 
        console.log(this.$route);
        if (!this.$route.meta.keepAlive) {
          if (this.$route.meta.zhuangTai) {
            // this.q_formDatas.zhuangTai=this.$route.meta.zhuangTai
            this.q_formDatas.zhuangTai = null
          }
          this.getTotal()
          this.getList(this.q_formDatas)

        } else {//如果keepalive==true
          console.log(this.$route.params.isBack);
          if (!this.$route.params.isBack) {
            this.getTotal()
            this.getList(this.q_formDatas)
          }
          this.isJump = false
        }


      },
      deep: true,
      immediate: true
    }
  },
  beforeRouteLeave (to, from, next) {
    if (this.isJump) {
      from.meta.keepAlive = true
    } else {
      from.meta.keepAlive = false
    }
    next();
  },
  mounted () {
    // this.getTotal()
    // this.getList(this.q_formDatas)

  },
  methods: {
    formatParms () {
      let sbdata = JSON.parse(JSON.stringify(this.q_formDatas))
      for (let key in sbdata) {
        console.log(key, sbdata[key]);
        if (!sbdata[key]) {
          sbdata[key] = null
        }

        if (key == 'purOrderNo' || key == 'manufacturerZh') {
          if (sbdata[key] == null) {
            sbdata[key] = `%%`
          } else {
            sbdata[key] = `%${sbdata[key]}%`
          }

        }
      }
      return sbdata
    },
    // 初始化页面时得到总数
    async getTotal () {
      let pages = ''
      pages = await getByConditionsCount(this.formatParms())
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal = (showTotal) => { return `共 ${showTotal} 条` }
      }
    },
    // 初始化查询时的数据列表
    async getList (params) {
      console.log('请求列表时传入的数据', this.formatParms())
      let actionBtn = ['订单明细']
      this.loading = true
      let listdata = []
      let res = ''
      res = await getByConditions(this.formatParms(), this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        // const resdata=[{pid:'9321093801',saleOrderNo:'qqq'}]
        for (let item of resdata) {
          switch (item.saleOrderState) {
            case '已配送':
              actionBtn = ['修改配送']
              break
            default:
              actionBtn = ['配送']
          }
          listdata.push({
            key: item.pid,
            action: actionBtn,
            ...item
          }
          )
        }
        this.listdata = listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 新增按钮 点击了新增
    onAddData () {
      this.$refs.modal.addModal()
    },
    // 关闭模态详细框
    handleModalCancel () {
    },
    // 模态详细框提交按钮
    handleModalSaveOk () {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction (text, record, index) {
      if (text == '订单明细') {
        // this.$refs.viewModal.showModal(record.pid,record)
        // this.showConfirm(record)
      } else if (text == '配送') {
        this.$router.push({
          name: 'mergeOrder',
          params: {
            isJump: false,
            pathName: this.$route.name,
            goodsId: [record]
          }
        })
      } else if (text == '修改配送') {
        // this.$refs.modal.editModal(record.pid,record)
      }
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 查询按钮
    onFind () {
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },

    onTouchlinkCell (text, record, index, link) {
      console.log(record);
      if (link == 'saleOrderNo') {
        this.$refs.viewSaleOrderModal.showModal(record.pid, record)
      }
    },
    // 多选批量操作
    onselectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.action[0] != '确认') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onDelectData () {
      if (this.selectedRows.length) {
        this.showDelConfirm(this.selectedRows)
      } else {
        this.$message.warning({ content: '未选择要删除的商品', duration: 3 })
      }
    },
    showDelConfirm (val, type) {
      let datas = []
      if (type == '1') {
        datas[0] = val
      } else {
        datas = val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk () {
          let reqArr = []
          let key = 'self'
          for (const item of datas) {
            reqArr.push(that.delOrder(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content: '采购订单' + item.data.saleOrderNo + '删除成功', duration: 3 })
              } else {
                that.$message.error({ content: '采购订单' + item.data.saleOrderNo + '删除失败，原因：' + item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content: '操作出错:' + err, duration: 3 })
          })
        },
        onCancel () { },
      });
    },
    async delOrder (val) {
      let res = await deleteInfo(val)
      return res
    },
    onMerge () {
      if (!this.selectedRows.length) {
        this.$message.warning({ content: '未选择要合并的记录', duration: 3 })
      } else {
        this.$router.push({
          name: 'mergeOrder',
          params: {
            isJump: false,
            pathName: this.$route.name,
            goodsId: this.selectedRows
          }
        })
      }
    },
    // 搜索栏选择下拉select触发搜索val[0]表示选中的record中的pid,val[1]表示选中的record全部信息
    onChangeType (name, val) {
      // console.log('formName',name)
      // console.log('val',val)
      switch (name) {
        case 'pid':
          if (!val[0]) {
            this.q_formDatas.pid = null
          }
          this.onFind()
          break
        case 'customerPid':
          if (!val) {
            this.q_formDatas.customerPid = null
          }
          this.onFind()
          break
        case 'saletype':
          if (!val) {
            this.q_formDatas.saletype = null
          }
          this.onFind()
          break
      }
    },
    onBatchAudit () {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已确认的记录，请选择未确认的记录', duration: 3 })
        } else {
          this.showConfirm(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要审核的记录', duration: 3 })
      }
    }
  },
}
</script>

<style>
</style>